<script setup>
import axios from "axios";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
onMounted(() => {
  userId.value = localStorage.getItem("userId");
  console.log(userId.value);
  getUserDate();
  getMesDate();
});
const prompt = ref("留下点什么吧~");
const RepPrompt = ref("");
// 留言列表
const messages = ref([]);
let userId = ref("");
let userArr = ref([]);
const isReplies = ref(false);
const repId = ref("");
const toWho = ref("");

//获取用户数据
const getUserDate = async () => {
  let { data } = await axios.get(`http://localhost:3000/userList/${userId.value}`);
  userArr.value = data;
};
//获取留言数据
const getMesDate = async () => {
  let { data } = await axios.get("http://localhost:3000/messages/");
  messages.value = data.reverse();
};

//更新数据
const uploadData = async () => {
  await axios.post(`http://localhost:3000/messages`, {
    userId: userArr.value.id,
    username: userArr.value.username,
    img: userArr.value.img,
    time: new Date().toLocaleString(),
    content: userInput.value,
    likes: [],
    replies: [],
  });
  getMesDate();
};

// 用户输入内容
const userInput = ref("");

// 发送留言
const sendMes = async () => {
  if (!userInput.value.trim()) {
    ElMessage.warning("请输入内容~");
    return;
  }
  if (!isReplies.value) {
    uploadData();
  } else {
    let { data } = await axios.get(`http://localhost:3000/messages/${repId.value}`);
    let rep = [];
    rep = data;
    let Ruser = {
      id: +new Date(),
      userId: userArr.value.id,
      username: userArr.value.username,
      img: userArr.value.img,
      time: new Date().toLocaleString(),
      content: userInput.value,
      likes: [],
      toWho: toWho.value,
    };
    if (rep.replies.length == 0) {
      rep.replies.push(Ruser);
    } else {
      // console.log(likeArr.likes);
      let flag = rep.replies.findIndex((item) => item == userArr.value.id);
      if (flag > -1) {
        // console.log(flag);
        rep.replies.splice(flag, 1);
      } else {
        rep.replies.push(Ruser);
      }
    }
    await axios.patch(`http://localhost:3000/messages/${repId.value}`, {
      replies: rep.replies,
    });
    getMesDate();
  }
  userInput.value = "";
};

// 点赞
const likeMes = async (id, isReply, replyId) => {
  const { data } = await axios.get(`http://localhost:3000/messages/${id}`);
  // console.log(data);
  if (isReply) {
    const replyIndex = data.replies.findIndex((item) => item.id == replyId);
    if (replyIndex > -1) {
      const reply = data.replies[replyIndex];
      toggleLike(reply.likes);
      data.replies[replyIndex] = reply;
    }
    await axios.patch(`http://localhost:3000/messages/${id}`, {
      replies: data.replies,
    });
  } else {
    toggleLike(data.likes);
    await axios.patch(`http://localhost:3000/messages/${id}`, {
      likes: data.likes,
    });
  }
  getMesDate();
};

//点赞切换
const toggleLike = (likes) => {
  const index = likes.findIndex((item) => item == userArr.value.id);
  if (index > -1) {
    //取消点赞
    likes.splice(index, 1);
  } else {
    //添加点赞
    likes.push(userArr.value.id);
  }
};

// 切换成回复
const changeReply = async (rid, id, Who) => {
  console.log(Who);
  let { data } = await axios.get(`http://localhost:3000/messages/${id}`);
  console.log(data);
  repId.value = id;
  toWho.value = Who;
  RepPrompt.value = `你回复“${toWho.value}”`;
  isReplies.value = true;
  console.log(isReplies.value);
  userInput.value = "";
};
</script>

<template>
  <!-- 用户输入 -->
  <div class="message" v-if="userId">
    <div class="inputDiv">
      <textarea
        v-model="userInput"
        :placeholder="prompt"
        v-if="!isReplies"
        @keyup.enter="sendMes"
      ></textarea>
      <textarea
        v-model="userInput"
        :placeholder="RepPrompt"
        v-else
        @keyup.enter="sendMes"
      ></textarea>
      <div class="send" @click="sendMes">{{ isReplies ? "回复" : "留言" }}</div>
      <div class="rep" @click="isReplies = false" v-if="isReplies">取消回复</div>
    </div>
    <!-- 留言的信息 -->
    <div class="userMes">
      <ul class="userMesUl">
        <li class="userMesLi" v-for="item in messages" :key="item.id">
          <img :src="item.img" alt="" />
          <div class="mes">
            <div class="time">
              <span>{{ item.username }}</span>
              <span>{{ item.time }}</span>
            </div>
            <div class="mesC">{{ item.content }}</div>
            <div class="mesB">
              <div class="print" @click="likeMes(item.id, false, item.id)">
                <i
                  class="iconfont"
                  :class="
                    item.likes.findIndex((like) => like === userArr.id) > -1
                      ? 'icon-dianzan_kuai'
                      : 'icon-dianzan'
                  "
                ></i>
                赞 ({{ item.likes.length }})
              </div>
              <div class="reply" @click="changeReply(item.id, item.id, item.username)">
                <i class="iconfont icon-huifu"></i> 回复
              </div>
            </div>
          </div>

          <!-- 回复区域 -->
          <ul v-if="item.replies.length > 0" class="repUl">
            <li v-for="reply in item.replies" :key="reply" class="repLi">
              <img :src="reply.img" alt="" />
              <div class="mes">
                <div class="time">
                  <span>{{ reply.username }}&nbsp;回复了&nbsp;{{ reply.toWho }}</span>
                  <span>{{ reply.time }}</span>
                </div>
                <div class="mesC">{{ reply.content }}</div>
                <div class="mesB">
                  <div class="print" @click="likeMes(item.id, true, reply.id)">
                    <i
                      class="iconfont"
                      :class="
                        reply.likes.findIndex((like) => like === userArr.id) > -1
                          ? 'icon-dianzan_kuai'
                          : 'icon-dianzan'
                      "
                    ></i>
                    赞 ({{ reply.likes.length }})
                  </div>
                  <div
                    class="reply"
                    @click="changeReply(reply.id, item.id, reply.username, false)"
                  >
                    <i class="iconfont icon-huifu"></i> 回复
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
  <el-empty description="登录后查看" v-else />
</template>

<style scoped>
@import url("/src/assets/style/message/message.scss");
</style>
<style>
.el-empty {
  height: 60%;
}
/* 滚动条整体样式 */
::-webkit-scrollbar {
  width: 3px;
  /* 滚动条宽度 */
  height: 0px;
  /* 横向滚动条高度 */
}

/* 滚动条滑块样式 */
::-webkit-scrollbar-thumb {
  background: #cd297d;
  /* 滑块颜色 */
  border-radius: 5px;
  /* 滑块圆角 */
}

/* 滚动条轨道样式 */
::-webkit-scrollbar-track {
  background: #f0f0f0;
  /* 滚动条轨道颜色 */
  border-radius: 5px;
  /* 轨道圆角 */
}
</style>
